//
//  TSZNetWorkTools.swift
//  微博天下

import UIKit
import AFNetworking
import SDWebImage
 /// 定义一个错误类别的标记 ，一般公司都会有这样的错误.h
private let TSZErrorDomainName = "com.tszblog.netWork"

//网络错误枚举
private enum TSZNetworkingError: Int{
    case emptyDataError = -1
    case emptyTokenError = -2
    
    //使用错误的描述
    private var errorDescrption: String {
        switch self{
        case.emptyDataError :return  "空数据"
        case.emptyTokenError :return  "token为空"
        }
    }
    //根据枚举类型，返回对应的错误
    private func error() ->NSError {
        return NSError(domain: TSZErrorDomainName, code: rawValue, userInfo: [TSZErrorDomainName :errorDescrption])
    }
}

//网络访问方法
private enum TSZNetMethod: String {
    case POST = "POST"
    case GET = "GET"
}

class TSZNetWorkTools: AFHTTPSessionManager {
    //MARK: - oAuth授权相关信息
    //微博上开发的客户端 id  申请应用时分配的AppKey。
    private var clientId = "2702821907"
    //回调路径 授权回调地址，站外应用需与设置的回调地址一致，站内应用需填写canvas page的地址。
    var redirectURI = "http://www.baidu.com"
    //APP secret
    private var clientSecret = "3685e6f5fe7be58df593d3926127b785"
    
    //全局访问点
    static let sharedNetWorkTools: TSZNetWorkTools = {
        let instance = TSZNetWorkTools(baseURL: NSURL(string: "https://api.weibo.com/")!)
        instance.responseSerializer.acceptableContentTypes = NSSet(objects:"application/json", "text/json", "text/javascript", "text/plain" ) as Set<NSObject>
        return instance
    }()
    
    /**
    发送微博
    
    - parameter status : 要发送微博的文字
    - parameter finised: 完成的回调
    */
    //MARK: 发送一条没有图片的微博
    func sendMricoblog(status: String ,image: UIImage?,finised: TSZNetFinishedCallBack){
        
        guard var params = isTokenDict(finised) else{
            return
        }
        params["status"] = status
        
        if image == nil {
            // post发布微博
            request(TSZNetMethod.POST, urlString: "2/statuses/update.json", prarms: params, finished: finised)
        }else{
            uploadImaged(image!, urlString: "https://upload.api.weibo.com/2/statuses/upload.json", prarms: params, finished: finised)
        }
        
    }
    //MARK: -获取当前登录用户及其所关注用户的最新微博
    func loadHomeMicroblog(since_id: Int, max_id: Int, finised:TSZNetFinishedCallBack){
        //判断token是否存在
        guard var params = isTokenDict(finised) else{
            return
        }
        
        print( "传到net上的\(since_id)")
        if since_id > 0{
            params["since_id"] = since_id
        }
        
        if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        
        let urlString = "2/statuses/home_timeline.json"
        request(TSZNetMethod.GET, urlString: urlString, prarms: params, finished: finised)
    }
    
    //加载用户数据
    func loadUserInfo(uid: String ,finised:TSZNetFinishedCallBack){
        //使用新语法去判断guard
        guard var params = isTokenDict(finised) else{
            return
        }
        //测试路径
        let urlString = "2/users/show.json"
        //参数
       params["uid"] = uid
        request(TSZNetMethod.GET, urlString: urlString, prarms: params, finished: finised)
    }
    
    //MARK - 判断token是否为空
    private func isTokenDict(finised: TSZNetFinishedCallBack) ->[String: AnyObject]?{
        if TSZUserAcountModel.sharedUserAccount()?.access_token == nil{
            //判断token是否存在，把错误抛出
            let error = TSZNetworkingError.emptyTokenError.error()
            finised(result: nil, error: error)
            
            return nil
        }
        return ["access_token" :TSZUserAcountModel.sharedUserAccount()!.access_token!]
    }
    
    //根据oAuth 授权路径  ,这个路径可以出现授权的界面 ，如果授权成功，就会回调redirectURI ，这个地址
    var oauthURL :NSURL{
        return NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectURI)")!
    }
    
    //使用authorization_code 授权码获取，Access token  访问令牌 ，定义函数
    func loadAccessToken(AuthorizationCode:String , finised:(result: [String:AnyObject]?, error:NSError?) ->()){
        //访问令牌的请求地址
        let urlString  = "https://api.weibo.com/oauth2/access_token"
        
        //实现 post 请求的 必选  参数，使用字典去存储
        let parames = [
            "client_id" : clientId,
            "client_secret" : clientSecret,
            "grant_type" :"authorization_code",//授权码
            "code" : AuthorizationCode,
            "redirect_uri" :redirectURI]
        
        //把上述的post请求参数使用到post请求中
        request(TSZNetMethod.POST, urlString: urlString, prarms: parames, finished: finised)
    }
    
    //MARK:- 封装AFN 网络方法，便于替换网络访问访问，第三方框架的网络代码都 
    /**
    * 网络回调类型别名 int x = 10       int x  x =10
    */
    typealias TSZNetFinishedCallBack = (result: [String : AnyObject]? , error: NSError?) ->()
    
    private func request(method: TSZNetMethod , urlString: String ,prarms: [String : AnyObject],finished:TSZNetFinishedCallBack){
        //定义成功的闭包
        let successCallBack: (NSURLSessionDataTask! , AnyObject!) ->Void = {(_,JSON) ->Void in
            if let result = JSON as? [String : AnyObject]{
                
                //回调
                finished(result: result, error: nil)
            }else{
                //没有错误，但是没有结果 ，可能是一些 硬件或者后台的问题，需要处理
                print("没有数据  GET  Request \(urlString)")

                finished(result: nil, error: TSZNetworkingError.emptyDataError.error())
            }
        }
        //定义错误的闭包
        let failedCallBack:(NSURLSessionDataTask! , NSError!) ->Void = {(_,error)
            -> Void in
            finished(result: nil, error: error)
        }
        
        //根据method来选择执行方法
        switch method {
        case.GET:
            GET(urlString, parameters: prarms, success: successCallBack, failure: failedCallBack)
        case.POST:
            POST(urlString, parameters: prarms, success: successCallBack, failure: failedCallBack)
        }
    }
    
    //上传图像
    private func uploadImaged(image: UIImage , urlString: String ,prarms: [String : AnyObject],finished: TSZNetFinishedCallBack){
        
        //定义成功的闭包
        let successCallBack: (NSURLSessionDataTask! , AnyObject!) ->Void = {(_,JSON) ->Void in
            if let result = JSON as? [String : AnyObject]{
                
                //回调
                finished(result: result, error: nil)
            }else{
                //没有错误，但是没有结果 ，可能是一些 硬件或者后台的问题，需要处理
                print("没有数据  GET  Request \(urlString)")
                
                finished(result: nil, error: TSZNetworkingError.emptyDataError.error())
            }
        }
        //定义错误的闭包
        let failedCallBack:(NSURLSessionDataTask! , NSError!) ->Void = {(_,error)
            -> Void in
            finished(result: nil, error: error)
        }
        
        //Mark: 利用post传值
        POST(urlString, parameters: prarms, constructingBodyWithBlock: { (formData) -> Void in
            
                //将image转换成二进制 数据
            let data = UIImagePNGRepresentation(image)!
            //构造数据体
            formData.appendPartWithFileData(data, name: "pic", fileName: "tm", mimeType: "application/octet-stream")
            
            }, success: successCallBack, failure: failedCallBack)
    }
    
}

